<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Gold
 * @package     Gold_Repay
 * @author   $Id$
 */

/**
 * Repay Controller
 */
class Gold_Repay_RepayController extends Mage_Core_Controller_Front_Action
{    
    /**
     * Update payment method (combined action for ajax and regular request)
     */
    public function savePaymentMethodAction()
    {
    	if (!isset($orderId)) {
            $orderId = (int) $this->getRequest()->getParam('order_id');
        }
    	if (!$this->_loadValidOrder($orderId))
    	{
    		return ;
    	}
        try {
            $repay = $this->_getRepay();
            $repay->savePayment($this->getRequest()->getParam('payment'));
                $this->loadLayout('repay_order_review');
                $this->getResponse()->setBody($this->getLayout()->getBlock('root')
                    ->setOrder($this->_getOrder($orderId))
                    ->toHtml());
                return;
        }
        catch (Exception $e) {
            $this->_getCatalogSession()->addError($e->getMessage());
        }
    }

	/**
     * Create order action
     */
    public function saveOrderAction()
    {
    	if (!isset($orderId)) {
            $orderId = (int) $this->getRequest()->getParam('order_id');
        }
    	if (!$this->_loadValidOrder($orderId))
    	{
    		return ;
    	}
        $result = array();
        try {                        
            $redirectUrl = $this->_getRepay()->getRedirectUrl();
            $result['success'] = true;
            $result['error']   = false;

        }  catch (Exception $e) {
            Mage::logException($e);
            Mage::helper('checkout')->sendPaymentFailedEmail($this->_getRepay()->getOrder(), $e->getMessage());
            $result['success']  = false;
            $result['error']    = true;
            $result['error_messages'] = $this->__('There was an error processing your order. Please contact us or try again later.');
        }

        if (isset($redirectUrl)) {
            $result['redirect'] = $redirectUrl;
        }

        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
    
	/**
     * Order success action
     */
    public function successAction()
    {
    	$orderId = (int) $this->getRequest()->getParam('order_id');
        if (!$orderId) {
            $this->_redirect('order/history');
            return;
        }
        
        $this->loadLayout();
        $this->_initLayoutMessages('checkout/session');
        Mage::dispatchEvent('repay_repay_controller_success_action', array('order_ids' => array($orderId)));
        $this->renderLayout();
    }
    
	/**
     * Try to load valid order by order_id and register it
     *
     * @param int $orderId
     * @return bool
     */
    protected function _loadValidOrder($orderId = null)
    {        
        if (!$orderId) {
            return false;
        }

        $order = Mage::getModel('repay/order')->load($orderId);

        if ($this->_canViewOrder($order)) {
            Mage::register('current_order', $order);
            return true;
        }
        else {
            return false;
        }
        return false;
    }
    
	/**
     * Check order view availability
     *
     * @param   Mage_Sales_Model_Order $order
     * @return  bool
     */
    protected function _canViewOrder($order)
    {
        $customerId = Mage::getSingleton('customer/session')->getCustomerId();
        $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates();
        if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId)
            && in_array($order->getState(), $availableStates, $strict = true)
            ) {
            return true;
        }
        return false;
    }
    
    

    /**
     * Return catalog session object
     *
     * @return Mage_Catalog_Model_Session
     */
    private function _getCatalogSession()
    {
        return Mage::getSingleton('catalog/session');
    }

    /**
     * Return sales order object
     *
     * @return Gold_Repay_Model_Order
     */
    private function _getOrder($orderId)
    {
        if (!$this->_order) {
            $this->_order = Mage::getModel('repay/order')->load($orderId);
        }
        return $this->_order;
    }
    
    /**
     * Return repay quote object
     *
     * @return Gold_repay_Model_Repay
     */
    private function _getRepay()
    {
    	return Mage::getSingleton('repay/order_repay');
    } 

	/**
     * Initialize coupon
     */
    public function expressCouponPostAction()
    {
        /**
         * No reason continue with empty shopping cart
         */
        if (!$this->_getCart()->getQuote()->getItemsCount()) {
            $this->_redirect('paypal/express/review');
            return;
        }

        $couponCode = (string) $this->getRequest()->getParam('coupon_code');
        if ($this->getRequest()->getParam('remove') == 1) {
            $couponCode = '';
        }
        $oldCouponCode = $this->_getQuote()->getCouponCode();

        if (!strlen($couponCode) && !strlen($oldCouponCode)) {
            $this->_redirect('paypal/express/review');
            return;
        }

        try {
            $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
            $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
                ->collectTotals()
                ->save();

            if ($couponCode) {
                if ($couponCode == $this->_getQuote()->getCouponCode()) {
                    $this->_getPaypalSession()->addSuccess(
                        $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode))
                    );
                }
                else {
                    $this->_getPaypalSession()->addError(
                        $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode))
                    );
                }
            } else {
                $this->_getPaypalSession()->addSuccess($this->__('Coupon code was canceled.'));
            }

        } catch (Mage_Core_Exception $e) {
            $this->_getPaypalSession()->addError($e->getMessage());
        } catch (Exception $e) {
            $this->_getPaypalSession()->addError($this->__('Cannot apply the coupon code.'));
            Mage::logException($e);
        }

        $this->_redirect('paypal/express/review');
    }
    
	/**
     * Retrieve shopping cart model object
     *
     * @return Mage_Checkout_Model_Cart
     */
    protected function _getCart()
    {
        return Mage::getSingleton('checkout/cart');
    }
    
	/**
     * Get current active quote instance
     *
     * @return Mage_Sales_Model_Quote
     */
    protected function _getQuote()
    {
        return $this->_getCart()->getQuote();
    }
    
	/**
     * Get checkout session model instance
     *
     * @return Mage_Checkout_Model_Session
     */
    protected function _getPaypalSession()
    {
        return Mage::getSingleton('paypal/session');
    }
}
